/**
 * 项目名称:
 *
 * @Author: 夏国倩
 * @Date: 2023/10/10 11:44
 * @Copyright
 */
package IO2;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
read(byte[] b)
从该输入流读取最多 b.length个字节的数据为字节数组
 */
public class FileInputStreamTest3 {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("E:\\code\\TestDemo\\src\\demo\\IO2\\temp");
            //开始读，采用byte数组，一次读取多个字节。最多读取“数组”.length个字节
            byte[] bytes = new byte[4]; //准备一个长度为4的byte数组，一次最多读取4个字节
            //这个方法的返回值是：读取到的字节数量（不是字节本身）

            int readCount = fis.read(bytes); //第二次读到了4个字节
            System.out.println(readCount); //4
            //将字节数组转换成字符串
            //System.out.println(new String(bytes)); //abcd
            System.out.println(new String(bytes, 0, 4)); //abcd

            readCount = fis.read(bytes); //第二次读到了2个字节
            System.out.println(readCount); //2
            //System.out.println(new String(bytes)); //efcd
            System.out.println(new String(bytes, 0, 2)); //ef

            readCount = fis.read(bytes); //一个字节都没有读到时返回-1
            System.out.println(readCount); //-1

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
